#include "log.h"

using namespace std;

FILE *logFile;//日志文件指针
char buff[1024*64];//64k缓冲区

bool log_open(const char *file_path){
    logFile = fopen(file_path,"a+");
    if(logFile!=NULL){
        setvbuf(logFile,buff,_IOFBF,sizeof(buff));
        return true;
    }
    return false;
}

void log_print(const char *mes){
    time_t timer = time(0);
    struct tm cur_time;
    localtime_r(&timer, &cur_time); // 可重入的localtime

    string log_message; // 头部信息
    // 添加时间信息
    log_message += to_string(cur_time.tm_year + 1900);
    log_message.push_back('/');
    log_message += to_string(cur_time.tm_mon + 1);
    log_message.push_back('/');
    log_message += to_string(cur_time.tm_mday);
    log_message.push_back(' ');
    log_message += to_string(cur_time.tm_hour);
    log_message.push_back(':');
    log_message += to_string(cur_time.tm_min);
    log_message.push_back(':');
    log_message += to_string(cur_time.tm_sec);
    log_message.push_back(' ');

    log_message.append(mes); // 信息内容追加到时间后面

    if(fputs(log_message.c_str(), logFile)==EOF){
        printf("写入日志失败\n");
        exit(1);
    }
    fflush(logFile);
}

void log_close(){
    if(logFile != NULL){
        fflush(logFile);
        fclose(logFile);
    }
}
